package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.gap.cache.redis.RedisCache;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.CmJoinInfo;
import com.mingqijia.gassafety.db.entity.DtuDataStatistics;
import com.mingqijia.gassafety.db.entity.JvInfo;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.mapper.CmJoinInfoMapper;
import com.mingqijia.gassafety.db.mapper.DtuDataStatisticsMapper;
import com.mingqijia.gassafety.db.mapper.JvInfoMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.DtuDataStatisticsRequest;
import com.mingqijia.gassafety.webserver.request.JvInfoRequest;
import com.mingqijia.gassafety.webserver.response.CompanyResponse;
import com.mingqijia.gassafety.webserver.response.DtuDataStatisticsResponse;
import com.mingqijia.gassafety.webserver.response.JvInfoResponse;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import com.mingqijia.gassafety.webserver.service.JvInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 开通企业列表 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2023-02-10
 */
@Slf4j
@Service
public class JvInfoServiceImpl extends ServiceImpl<JvInfoMapper, JvInfo> implements JvInfoService {

    @Autowired
    CompanyService companyService;

    @Autowired
    ConfigureHolder holder;

    @Autowired
    DtuDataStatisticsMapper dtuDataStatisticsMapper;

    @Autowired
    CmJoinInfoMapper cmJoinInfoMapper;

    @Autowired
    RedisCache redisCache;

    @Override
    public PageUtil<JvInfoResponse> getList(JvInfoRequest req) {
        LambdaQueryWrapper<JvInfo> lqw = new LambdaQueryWrapper<>();
        lqw.like(!StringUtils.isEmpty(req.getName()), JvInfo::getName, req.getName())
                .eq(JvInfo::getIsDeleted, Constants.IS_DELETED_FALSE);
        if (!StringUtils.isEmpty(req.getArea()) && !"00".equals(req.getArea())) {
            lqw.eq(JvInfo::getArea, req.getArea());
        }
        lqw.orderByDesc(JvInfo::getCreatedAt);
        Page<JvInfo> page = PageHelper.startPage(req.getPage(), req.getPageSize());
        List<JvInfo> list = this.list(lqw);
        List<DictionaryItemRespDTO> areaList = holder.getDictionaryByKey(Constants.DICTIONARY_JV_AREA);
        List<JvInfoResponse> jvInfoResponses = list.stream().map(item -> {
            JvInfoResponse response = new JvInfoResponse();
            BeanUtils.copyProperties(item, response);
            DictionaryItemRespDTO dto = areaList.stream().filter(a -> a.getValue().equals(item.getArea()))
                    .collect(Collectors.toList()).get(0);
            response.setAreaName(dto.getName());
            return response;
        }).collect(Collectors.toList());
        PageUtil pageInfo = new PageUtil<>(req.getPage(), req.getPageSize(), page.getTotal(), jvInfoResponses);
        return pageInfo;
    }

    @Override
    public List<DtuDataStatisticsResponse> getDtuList(DtuDataStatisticsRequest response) {
        LambdaQueryWrapper<DtuDataStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DtuDataStatistics::getIsDeleted, Constants.IS_DELETED_FALSE);
        queryWrapper.orderByDesc(DtuDataStatistics::getCreatedAt);
        List<DtuDataStatistics> dtuData = dtuDataStatisticsMapper.selectList(queryWrapper);

        ArrayList<DtuDataStatisticsResponse> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(dtuData)) {
            Map<String, List<DtuDataStatistics>> listMap = dtuData.stream().collect(Collectors.groupingBy(DtuDataStatistics::getSpId));
            for (String s : listMap.keySet()) {
                List<DtuDataStatistics> dtuDataStatistics = listMap.get(s);
                DtuDataStatisticsResponse dtuDataResponse = new DtuDataStatisticsResponse();
                dtuDataResponse.setCompanyName(dtuDataStatistics.get(0).getCompanyName());
                for (DtuDataStatistics dtuDataStatistic : dtuDataStatistics) {
                    if (dtuDataStatistic.getEquipmentType().equals(EquipmentType.HOME_GAS_DETECTOR.getCode())) {
                        dtuDataResponse.setHomeRegisterNum(dtuDataStatistic.getRegisterNum());
                        dtuDataResponse.setHomeLiberalNum(dtuDataStatistic.getLiberalNum());
                        continue;
                    } else if (dtuDataStatistic.getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                        dtuDataResponse.setGasRegisterNum(dtuDataStatistic.getRegisterNum());
                        dtuDataResponse.setGasLiberalNum(dtuDataStatistic.getLiberalNum());
                        continue;
                    } else if (dtuDataStatistic.getEquipmentType().equals(EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode())) {
                        dtuDataResponse.setIndependentRegisterNum(dtuDataStatistic.getRegisterNum());
                        dtuDataResponse.setIndependentLiberalNum(dtuDataStatistic.getLiberalNum());
                        continue;
                    } else if (dtuDataStatistic.getEquipmentType().equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
                        dtuDataResponse.setPointRegisterNum(dtuDataStatistic.getRegisterNum());
                        dtuDataResponse.setPointLiberalNum(dtuDataStatistic.getLiberalNum());
                        continue;
                    }
                }
                dtuDataResponse.setRegisterNumSum(dtuDataResponse.getGasRegisterNum() + dtuDataResponse.getHomeRegisterNum()
                        + dtuDataResponse.getPointRegisterNum() + dtuDataResponse.getIndependentRegisterNum());
                dtuDataResponse.setLiberalNumSum(dtuDataResponse.getGasLiberalNum() + dtuDataResponse.getHomeLiberalNum()
                       + dtuDataResponse.getIndependentLiberalNum() + dtuDataResponse.getPointLiberalNum());
                list.add(dtuDataResponse);
            }
        }
        return list;
    }

    @Override
    public String getUpdateTime(){
        // 获取当天的0时0分0秒，并以yyyy-MM-dd HH:mm:ss 的格式展示
        LocalDateTime today = LocalDateTime.now().toLocalDate().atStartOfDay();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = today.format(formatter);
        return formattedDateTime;
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public void add(JvInfoRequest req) throws BizException {
        JvInfo jvInfo = new JvInfo();
        LambdaQueryWrapper<JvInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JvInfo::getSpId, req.getSpId()).eq(JvInfo::getIsDeleted, Constants.IS_DELETED_FALSE);
        JvInfo one = this.getOne(wrapper);
        if (one != null) {
            throw new BizException(one.getName() + "已存在！");
        }
        //企业名称
        LambdaQueryWrapper<CompanyEntry> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CompanyEntry::getId, req.getSpId());
        CompanyEntry companyEntry = companyService.getOne(lqw);

        jvInfo.setSpId(req.getSpId());
        jvInfo.setName(companyEntry.getName());
        jvInfo.setAlias(companyEntry.getName());
        jvInfo.setArea(req.getArea());
        jvInfo.setUserNums(req.getUserNums());
        jvInfo.setCivilUserNums(req.getCivilUserNums());
        jvInfo.setCreatedAt(new DateTime());
        jvInfo.setJoinTime(new DateTime());
        jvInfo.setUpdatedAt(new DateTime());
        jvInfo.setIntroduction(req.getIntroduction());
        this.save(jvInfo);
        //判断当前企业是否存在，不存在新增
        CmJoinInfo cmJoinInfo = getCmJoinInfo(req.getSpId());
        if (cmJoinInfo == null) {
            List<CmJoinInfo> joinInfoList = queryCmJoinInfo(req.getArea());
            CmJoinInfo joinInfo = new CmJoinInfo();
            joinInfo.setId(req.getSpId());
            if (CollectionUtil.isNotEmpty(joinInfoList)) {
                joinInfo.setPId(joinInfoList.get(0).getPId());
            }
            joinInfo.setRegionId(Integer.valueOf(req.getArea()));
            joinInfo.setSpName(companyEntry.getName());
            joinInfo.setSkUserNums(0);
            joinInfo.setGsscUserNumG(0);
            joinInfo.setGsscUserNumM(0);
            joinInfo.setGsscUserNums(0);
            joinInfo.setUpdateSource("1");
            joinInfo.setCreateTime(new Date());
            if (!StringUtils.isEmpty(req.getIntroduction()) && req.getIntroduction().contains(",")) {
                String[] split = req.getIntroduction().split(",");
                if (split.length == 2) {
                    joinInfo.setLon(new BigDecimal(split[0]));
                    joinInfo.setLat(new BigDecimal(split[1]));
                } else {
                    joinInfo.setLon(new BigDecimal(0));
                    joinInfo.setLat(new BigDecimal(0));
                }
            } else {
                joinInfo.setLon(new BigDecimal(0));
                joinInfo.setLat(new BigDecimal(0));
            }
            log.info("joinInfo的值为:{}", joinInfo);
            cmJoinInfoMapper.insert(joinInfo);
        } else {
            Integer region = Integer.valueOf(req.getArea());
            if (region != cmJoinInfo.getRegionId()) {
                cmJoinInfo.setRegionId(region);
                List<CmJoinInfo> joinInfoList = queryCmJoinInfo(req.getArea());
                if (CollectionUtil.isNotEmpty(joinInfoList)) {
                    cmJoinInfo.setPId(joinInfoList.get(0).getPId());
                }
            }
            cmJoinInfo.setUpdateSource("1");
            cmJoinInfo.setUpdateTime(new Date());
            if (!StringUtils.isEmpty(req.getIntroduction()) && req.getIntroduction().contains(",")) {
                String[] split = req.getIntroduction().split(",");
                if (split.length == 2) {
                    cmJoinInfo.setLon(new BigDecimal(split[0]));
                    cmJoinInfo.setLat(new BigDecimal(split[1]));
                }
            }
            cmJoinInfoMapper.updateById(cmJoinInfo);
        }
        redisCache.deleteObject(Constants.GASSAFETY_REGION_SP_INFO);
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public void edit(JvInfoRequest req) {
        LambdaQueryWrapper<JvInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JvInfo::getSpId, req.getSpId()).eq(JvInfo::getIsDeleted, Constants.IS_DELETED_FALSE);
        JvInfo one = this.getOne(wrapper);
        if (one != null && one.getId() != req.getId()) {
            throw new BizException("已存在于当前列表！");
        }
        LambdaQueryWrapper<JvInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(JvInfo::getId, req.getId());
        JvInfo jvInfo = this.getOne(queryWrapper);
        LambdaQueryWrapper<CompanyEntry> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CompanyEntry::getId, req.getSpId());
        CompanyEntry companyEntry = companyService.getOne(lqw);
        jvInfo.setSpId(req.getSpId());
        jvInfo.setName(companyEntry.getName());
        jvInfo.setAlias(companyEntry.getName());
        jvInfo.setArea(req.getArea());
        jvInfo.setUserNums(req.getUserNums());
        jvInfo.setCivilUserNums(req.getCivilUserNums());
        jvInfo.setIntroduction(req.getIntroduction());
        jvInfo.setUpdatedAt(new DateTime());
        this.updateById(jvInfo);
        //判断当前企业是否存在，不存在新增
        CmJoinInfo cmJoinInfo = getCmJoinInfo(req.getSpId());
        if (cmJoinInfo == null) {
            List<CmJoinInfo> joinInfoList = queryCmJoinInfo(req.getArea());
            CmJoinInfo joinInfo = new CmJoinInfo();
            joinInfo.setId(req.getSpId());
            if (CollectionUtil.isNotEmpty(joinInfoList)) {
                joinInfo.setPId(joinInfoList.get(0).getPId());
            }
            joinInfo.setRegionId(Integer.valueOf(req.getArea()));
            joinInfo.setSpName(companyEntry.getName());
            joinInfo.setSkUserNums(0);
            joinInfo.setGsscUserNumG(0);
            joinInfo.setGsscUserNumM(0);
            joinInfo.setGsscUserNums(0);
            joinInfo.setUpdateSource("1");
            joinInfo.setCreateTime(new Date());
            if (!StringUtils.isEmpty(req.getIntroduction()) && req.getIntroduction().contains(",")) {
                String[] split = req.getIntroduction().split(",");
                if (split.length == 2) {
                    joinInfo.setLon(new BigDecimal(split[0]));
                    joinInfo.setLat(new BigDecimal(split[1]));
                } else {
                    joinInfo.setLon(new BigDecimal(0));
                    joinInfo.setLat(new BigDecimal(0));
                }
            } else {
                joinInfo.setLon(new BigDecimal(0));
                joinInfo.setLat(new BigDecimal(0));
            }
            cmJoinInfoMapper.insert(joinInfo);
        } else {
            Integer region = Integer.valueOf(req.getArea());
            if (region != cmJoinInfo.getRegionId()) {
                cmJoinInfo.setRegionId(region);
                List<CmJoinInfo> joinInfoList = queryCmJoinInfo(req.getArea());
                if (CollectionUtil.isNotEmpty(joinInfoList)) {
                    cmJoinInfo.setPId(joinInfoList.get(0).getPId());
                }
            }
            cmJoinInfo.setUpdateSource("1");
            cmJoinInfo.setUpdateTime(new Date());
            if (!StringUtils.isEmpty(req.getIntroduction()) && req.getIntroduction().contains(",")) {
                String[] split = req.getIntroduction().split(",");
                if (split.length == 2) {
                    cmJoinInfo.setLon(new BigDecimal(split[0]));
                    cmJoinInfo.setLat(new BigDecimal(split[1]));
                }
            }
            cmJoinInfoMapper.updateById(cmJoinInfo);
        }
        redisCache.deleteObject(Constants.GASSAFETY_REGION_SP_INFO);
    }

    @Override
    public void deleteById(Integer id) {
        LambdaQueryWrapper<JvInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(JvInfo::getId, id);
        JvInfo jvInfo = this.getOne(queryWrapper);
        LambdaUpdateWrapper<JvInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(JvInfo::getIsDeleted, Constants.IS_DELETED_TRUE)
                .eq(JvInfo::getId, id);
        this.update(updateWrapper);
        if (jvInfo != null) {
            //删除当前企业
            cmJoinInfoMapper.deleteById(jvInfo.getSpId());
            redisCache.deleteObject(Constants.GASSAFETY_REGION_SP_INFO);
        }
    }

    @Override
    public List<CompanyResponse> getCompanyList() {
        List<CompanyResponse> companyList = companyService.getCompanyList();
        return companyList;
    }

    /**
     * 根据spId查询当前企业
     * @param spId
     * @return
     */
    public CmJoinInfo getCmJoinInfo(String spId) {
        QueryWrapper<CmJoinInfo> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CmJoinInfo::getId, spId);
        CmJoinInfo joinInfo = cmJoinInfoMapper.selectOne(getCmJoinWrapper);
        return joinInfo;
    }

    /**
     * 根据regionId查询当前区域的企业
     * @param regionId
     * @return
     */
    public List<CmJoinInfo> queryCmJoinInfo(String regionId) {
        QueryWrapper<CmJoinInfo> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CmJoinInfo::getRegionId, regionId);
        List<CmJoinInfo> joinInfoList = cmJoinInfoMapper.selectList(getCmJoinWrapper);
        return joinInfoList;
    }
}
